package com.study.zk.lock.zk;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 惊群效应
 * 在集群规模较大的环境中带来的危害
 * 1. 巨大的服务器性能损耗
 * 2. 网络冲击
 * 3. 可能造成宕机
 *
 * @author: chenhs
 * @date: Created in 10:40 2020/2/4
 **/
public class ZkDistributeLock implements Lock {

    private String lockPath;

    private ZkClient client;

    public ZkDistributeLock(String lockPath) {
        this.lockPath = lockPath;
        this.client = new ZkClient("localhost:2181");
        this.client.setZkSerializer(new MyZkSerializer());
    }

    /**
     * 不会阻塞
     * @return
     */
    @Override
    public boolean tryLock() {
        //创建（临时）节点
        try {
            client.createEphemeral(lockPath);
        } catch (ZkNodeExistsException e) {
            return false;
        }
        return true;
    }

    @Override
    public void unlock() {
        client.delete(lockPath);
    }

    /**
     * 如果获取不到锁，阻塞等待
     */
    @Override
    public void lock() {
        if (!tryLock()){
            //没获得锁，阻塞自己
            waitForLock();

            //再次尝试
            lock();
        }
    }

    private void waitForLock() {

        CountDownLatch cdl = new CountDownLatch(1);

        IZkDataListener listener = new IZkDataListener() {
            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
                System.out.println("---------------收到节点被删除了--------------");
                cdl.countDown();
            }

            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {
            }
        };
        //注册监听
        client.subscribeDataChanges(lockPath, listener);

        //阻塞自己
        if (this.client.exists(lockPath)) {
            try {
                cdl.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //取消注册
        client.unsubscribeDataChanges(lockPath, listener);
    }


    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
